import * as ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { axios, injectStore } from "apis/module/axios";
import { persistor } from "apis/module/store";
import store from "apis/module/store";
import DevTools from "apis/module/store/DevTools";
import { disableReactDevTools } from "apis/module/store/DevTools";
import { setAppName, setAppVersion } from "apis/module/store/slices/appSlice";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import debug from "debug";
import BlankLayout from "@/layout/BlankLayout";
import { getAppPkgInfos, API_HOST } from "./config";
import "./store";

dayjs.locale("zh-cn");
injectStore(store);
axios.defaults.baseURL = API_HOST;

if (process.env.NODE_ENV !== "production") {
  // 控制下日志输出, 默认是 app:*
  // app2 不输出日志
  localStorage.debug = "app:*";
}

const logger = debug("app:start");
const appName = getAppPkgInfos().pkg.name;
const version = getAppPkgInfos().pkg.version;
const buildDateTime = getAppPkgInfos().pkg.buildDateTime;
logger("%o - v%o - b%o start...", appName, version, buildDateTime ?? "缺");

function renderApp() {
  console.log("[ 当前环境 REACT_APP_ENV : ]", process.env.REACT_APP_ENV);
  console.log("[ 当前环境 NODE_ENV : ]", process.env.NODE_ENV);
  const root = ReactDOM.createRoot(
    document.getElementById("application-root") as HTMLElement,
  );

  store.dispatch(setAppName(appName));
  store.dispatch(setAppVersion(version));

  root.render(
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <BlankLayout />

        {process.env.NODE_ENV === "development" && <DevTools />}
      </PersistGate>
    </Provider>,
  );
}

if (process.env.NODE_ENV !== "development") {
  // 该方案有效
  console.log = () => {};
  console.error = () => {};
  console.debug = () => {};

  disableReactDevTools();
}

renderApp();
